<script setup lang="ts">
import { Plus, Minus } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { getProject } from "@/api/financial/lists";
import FilePopup from "../file.vue";
import DetailsPopup from "../details.vue";
// 数据字典
interface Dicts {
    finance_order_award: [{ id: ""; name: ""; value: "" }]; // 奖罚情况
    if_payment_request: [{ id: ""; name: ""; value: "" }]; // 类型
}
const props = defineProps({
    disabled: { type: Boolean, default: true },
    mode: { type: String, default: "add" },
    dicts: { type: Object, required: true },
    isEdit: { type: Boolean, default: false },
});
const span = ref(6);
// 表单
const formRef = ref<FormInstance>();
const formDataTemplate = {
    flow_id: "", // 流程id
    project_id: "", // 项目id
    unit_id: "", // 请款单位id
    creator: "", // 请款发起人
    time: "", // 请款节点双向绑定的值
    node_start_time: "", // 请款节点开始时间
    node_end_time: "", // 请款节点结束时间
    node_output_value: 0, // 节点产值
    payment_ratio: 0, // 付款比例
    labor_cost: 0, // 应付人工费
    labor_cost_tax_points: 4.5, // 人工费税点
    invoice_amount: 0, // 劳务费发票
    remark: "", // 备注
    award: [{ award_id: "", type_id: "", amount: 0, remark: "" }], // 奖罚
    attachment: [], // 附件
    material_deduction_amount: 0, // 材料发票金额
};
const formData = ref(JSON.parse(JSON.stringify(formDataTemplate)));
const rules: FormRules = {
    project_id: [{ required: true, message: "" }],
    unit_id: [{ required: true, message: "" }],
    creator: [{ required: true, message: "" }],
    time: [{ required: true, message: "", trigger: "change" }],
    node_output_value: [{ required: true, message: "", trigger: "change" }],
    payment_ratio: [{ required: true, message: "", trigger: "change" }],
    labor_cost: [{ required: true, message: "", trigger: "change" }],
    labor_cost_tax_points: [{ required: true, message: "", trigger: "change" }],
    invoice_amount: [{ required: true, message: "", trigger: "change" }],
};
// 项目信息
interface ProjectInfoType {
    id: string;
    title: string;
    projectUnit: [{ unit_id: ""; unit_text: "" }];
    applicant_text: [{ id: ""; name: "" }];
}
const projectInfo = ref<ProjectInfoType[]>([]);
// 根据项目id 获取单位列表
const unitList = computed(() => {
    const project = projectInfo.value.find(project => {
        return project.id == formData.value.project_id;
    });
    return project ? project.projectUnit : [];
});
// lqy 根据查看的请款节点格式化时间
const detailObj=(time: any)=>{
 return time.length>0?`${time[0]}-${time[1]}`:''
}
// 根据单位id 获取单位名
const getUnitName = (unit_id: string) => {
    const res = unitList.value.find(item => item.unit_id == unit_id)!;
    return res ? res.unit_text : formData.value.unit_text;
};
// 根据项目id 获取项目名
const getProjectName = (project_id: string) => {
    const res = projectInfo.value.find(item => item.id == project_id)!;
    return res ? res.title : formData.value.project_text;
};
// 根据项目id 获取请款人列表
const creatorList = computed(() => {
    const project = projectInfo.value.find(project => {
        return project.id == formData.value.project_id;
    });
    return project ? project.applicant_text : [];
});
// 付款金额
const paymentAmount = computed(() => {
    const { node_output_value, payment_ratio } = formData.value;
    // 节点产值*付款比例
    const res = (node_output_value * (payment_ratio / 100)).toFixed(2);
    return +res;
});
// 应付人工款占比
const payPelpleBL = computed(() => {
    if (paymentAmount.value === 0) return 0;
    const { labor_cost } = formData.value;
    // 应付人工费/付款金额）*100%
    const res = ((labor_cost / paymentAmount.value) * 100).toFixed(2);
    return +res;
});
// 人工费扣税金额
const payTax = computed(() => {
    const { labor_cost, labor_cost_tax_points } = formData.value;
    let num = 0;
    let num1 = 0;
    formData.value.award?.forEach((item: any) => {
        // 获取人工罚款
        if (item.type_id == 1 && item.award_id == 2) {
            num = num + item.amount * 1;
        }
        // 获取人工奖励
        if (item.type_id == 1 && item.award_id == 1) {
            num1 = num1 + item.amount * 1;
        }
    });
    // 应付人工费-人工费罚款金额*人工费税点
    const res = ((labor_cost - num) * (labor_cost_tax_points / 100)).toFixed(2);
    return +res;
});
// 应付材料费(材料费发票金额) = 付款金额 - 应付人工费
const payMaterial = computed(() => {
    const { labor_cost } = formData.value;
    return labor_cost == 0 ? 0 : +(paymentAmount.value - labor_cost).toFixed(2);
});
// 应付材料费占比 =（应付材料费/付款金额）* 100%
const payMaterialBL = computed(() => {
    if (paymentAmount.value === 0) return 0;
    return ((payMaterial.value / paymentAmount.value) * 100).toFixed(2);
});
// 应实付款金额 = 付款金额 - 实扣人工费税费 - 惩罚 + 奖励
const payReal = computed(() => {
    const { labor_cost, labor_cost_tax_points } = formData.value;
    // 获取人工罚款
    let num = 0;
    // 获取人工奖励
    let num1 = 0;
    let cailiaofa = 0;
    let cailiaojiang = 0;
    formData.value.award?.forEach((item: any) => {
        if (item.type_id == 1 && item.award_id == 2) {
            num = num + item.amount * 1;
        }
        if (item.type_id == 1 && item.award_id == 1) {
            num1 = num1 + item.amount * 1;
        }
        if (item.type_id == 2 && item.award_id == 2) {
            cailiaofa = cailiaofa + item.amount * 1;
        }
        if (item.type_id == 2 && item.award_id == 1) {
            cailiaojiang = cailiaojiang + item.amount * 1;
        }
    });
    // （应付人工费 - 人工费罚款金额）-（应付人工费-人工费罚款金额）*人工费税点  + 人工费奖励金额  + 应付材料费+材料费奖励 - 材料费罚款
    return (
        labor_cost -
        num -
        (labor_cost - num) * (labor_cost_tax_points / 100) +
        num1 +
        payMaterial.value +
        cailiaojiang -
        cailiaofa
    );
});
// 删除奖罚
const handleDelete = (index: number) => {
    formData.value.award.splice(index, 1);
};
// 新增奖罚
const handleAddAward = () => {
    const { award } = formData.value;
    award.push({ award_id: "", type_id: "", amount: 0, remark: "" });
};
// 查看附件
const fileRef = shallowRef<InstanceType<typeof FilePopup>>();
const setFileFn = (item: any) => {
    formData.value.attachment = JSON.parse(JSON.stringify(item));
};
const handleFile = async () => {
    fileRef.value?.open();
};
// 详情
const detailsRef = ref();
const handleDetails = async (
    value: string,
    id: string,
    project_id?: string
) => {
    detailsRef.value?.open();
    detailsRef.value?.getAdminListss(value, id, project_id);
};
// 设置 请款单数据
const setFormData = async (data: any) => {
    if (typeof data === "number") {
        // 新增
        formData.value.flow_id = data;
        projectInfo.value = await getProject({ flow_id: data }); // 获取项目信息
    } else {
        projectInfo.value = await getProject({ flow_id: data?.flow_id });
        // 编辑
        formData.value = data;
        formData.value.time = [
            formData.value.node_start_time,
            formData.value.node_end_time,
        ];
        // 类型转换  lqy查看时保持单位一致
        // formData.value.node_output_value = formData.value.node_output_value;
        // formData.value.labor_cost = formData.value.labor_cost;
        // formData.value.invoice_amount = formData.value.invoice_amount;
        // formData.value.labor_cost_tax_points =
        //     +formData.value.labor_cost_tax_points;
    }
};
// 获取 请款单数据
const getFormData = async () => {
    try {
        await formRef.value?.validate();
        const params = JSON.parse(JSON.stringify(formData.value));
        formData.value = JSON.parse(JSON.stringify(formDataTemplate));
        params.node_start_time = params.time[0];
        params.node_end_time = params.time[1];
        params.award = JSON.stringify(params.award);
        params.attachment = JSON.stringify(params.attachment);
        return params;
    } catch (error) {
        console.log("🚀🚀🚀", error);
    }
};
// 清除 请款单数据
const clearFormData = () => {
    if (!formRef.value) return;
    formRef.value.resetFields();
    formData.value = JSON.parse(JSON.stringify(formDataTemplate));
};
defineExpose({ setFormData, getFormData, clearFormData });
</script>

<template>
    <el-form
        :model="formData"
        ref="formRef"
        :rules="rules"
        label-width="105px"
        label-position="right"
    >
        <template v-if="mode === 'edit'">
            <el-row>
                <el-col :span="span">
                    <el-form-item label="单据编号">
                        {{ formData.order_no }}
                    </el-form-item>
                </el-col>
                <el-col :span="span">
                    <el-form-item label="类型">
                        {{ formData.flow?.order_type_text }}
                    </el-form-item>
                </el-col>
                <el-col :span="span">
                    <el-form-item label="审核状态">
                        {{ formData.order_status_text }}
                    </el-form-item>
                </el-col>
                <el-col :span="span">
                    <el-form-item label="付款状态">
                        {{ formData.payment_status_text }}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="span">
                    <el-form-item label="创单人">
                        {{ formData.create_user }}
                    </el-form-item>
                </el-col>
                <el-col :span="span * 3">
                    <el-form-item label="创单时间">
                        {{ formData.create_time }}
                    </el-form-item>
                </el-col>
            </el-row>
        </template>
        <el-row>
            <el-col :span="span">
                <el-form-item label="项目名称" prop="project_id">
                    <el-select
                        v-if="!disabled"
                        v-model="formData.project_id"
                        size="small"
                    >
                        <el-option
                            v-for="item in projectInfo"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id"
                        />
                    </el-select>
                    <el-button
                        v-else
                        link
                        type="primary"
                        size="small"
                        @click="handleDetails('项目名称', formData.project_id)"
                    >
                        {{ getProjectName(formData.project_id) }}
                    </el-button>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="请款单位" prop="unit_id">
                    <el-select
                        v-if="!disabled"
                        v-model="formData.unit_id"
                        size="small"
                        filterable
                    >
                        <el-option
                            v-for="item in unitList"
                            :key="item.unit_id"
                            :label="item.unit_text"
                            :value="item.unit_id"
                        />
                    </el-select>
                    <el-button
                        v-else
                        link
                        type="primary"
                        size="small"
                        @click="
                            handleDetails(
                                '请款单位',
                                formData.unit_id,
                                formData.project_id
                            )
                        "
                    >
                        {{ getUnitName(formData.unit_id) }}
                    </el-button>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="请款发起人" prop="creator">
                    <el-select
                        v-if="!disabled"
                        :disabled="disabled"
                        v-model="formData.creator"
                        size="small"
                    >
                        <el-option
                            v-for="item in creatorList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                    <span> {{ formData.creator_user }}</span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="请款节点" prop="time">
                    <el-date-picker
                        v-if="!disabled"
                        v-model="formData.time"
                        type="daterange"
                        unlink-panels
                        range-separator="至"
                        size="small"
                        format="YYYY/MM/DD"
                        value-format="YYYY-MM-DD"
                    />
                    <!--lqy 修改查看节点的数据-->
                    <span v-else="disabled">{{detailObj(formData.time)}}</span>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="span">
                <el-form-item label="节点产值" prop="node_output_value">
                     <!--lqy 修改查看节点的数据-->
                    <span v-if="!disabled">
                    <el-input-number
                        v-model="formData.node_output_value"
                        :precision="2"
                        :min="0"
                        size="small"
                    />
                    <span style="margin-left: 5px">元</span>
                    </span>
                    <span v-else>{{formData.node_output_value}}元 </span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="付款比例" prop="payment_ratio">
                     <!--lqy 修改查看节点的数据-->
                    <span v-if="!disabled">
                    <el-input-number
                        v-model="formData.payment_ratio"
                        :precision="2"
                        :min="0"
                        :max="100"
                        size="small"
                    />
                    <span style="margin-left: 5px">%</span>
                    </span>
                    <span v-else> <span>{{formData.payment_ratio}}%</span></span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="付款金额">
                    <span>{{ paymentAmount }}</span>
                    <span>元</span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="应付人工费" prop="labor_cost">
                     <!--lqy 修改查看节点的数据-->
                    <span v-if="!disabled">
                     <el-input-number
                        v-model="formData.labor_cost"
                        :precision="2"
                        :min="0"
                        :max="paymentAmount"
                        size="small"
                    />
                    <span style="margin-left: 5px">元</span>
                    </span>
                    <span v-else>{{formData.labor_cost}}元</span>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="span">
                <el-form-item label="应付人工款占比">
                    <span>{{ payPelpleBL }}</span>
                    <span>%</span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="人工费稅点" prop="labor_cost_tax_points">
                     <!--lqy 修改查看节点的数据-->
                    <span v-if="!disabled">
                      <el-input-number
                        v-model="formData.labor_cost_tax_points"
                        :precision="2"
                        :min="0"
                        :max="100"
                        size="small"
                    />
                    <span style="margin-left: 5px">%</span>
                    </span>
                    <span v-else>{{formData.labor_cost_tax_points}}%</span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="人工费扣税金额">
                    <span>{{ payTax }}</span>
                    <span>元</span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="劳务票发票" prop="invoice_amount">
                     <!--lqy 修改查看节点的数据-->
                    <span v-if="!disabled">
                     <el-input-number
                        v-model="formData.invoice_amount"
                        :precision="2"
                        :min="0"
                        :max="formData.labor_cost"
                        size="small"
                    />
                    <span style="margin-left: 5px">元</span>
                    </span>
                    <span v-else>{{formData.invoice_amount}}元</span>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="span">
                <el-form-item label="应付材料费">
                    <span>{{ payMaterial }}</span>
                    <span>元</span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="应付材料费占比">
                    <span>{{ payMaterialBL }}</span>
                    <span>%</span>
                </el-form-item>
            </el-col>
            <el-form-item
                label="材料费发票金额"
                prop="material_deduction_amount"
            >
             <!--lqy 修改查看节点的数据-->
            <span v-if="!disabled">
             <el-input-number
                    v-model="formData.material_deduction_amount"
                    :precision="2"
                    :min="0"
                    :max="formData.labor_cost"
                    size="small"
                />
                <span style="margin-left: 5px">元</span>
            </span>
              <span v-else>{{formData.material_deduction_amount}}元</span>
            </el-form-item>
            <!-- <el-col :span="span">
                <el-form-item label="材料费发票金额">
                    <span>{{ payMaterialBL }}</span>
                    <span>元</span>
                </el-form-item> -->
            <!-- </el-col> -->
            <el-col :span="span">
                 <!--lqy 修改查看节点的数据-->
                <div class="flex justify-end" v-if="!disabled">
                    <el-button
                        type="primary"
                        :icon="Plus"
                        circle
                        size="small"
                        @click="handleAddAward"
                    />
                </div>
            </el-col>
        </el-row>
        <el-row v-for="(item, index) in formData.award" :key="index">
            <el-col :span="span">
                <el-form-item label="奖罚情况">
                     <!--lqy 修改查看节点的数据-->
                    <el-select
                        v-if="!disabled"
                        v-model="item.award_id"
                        size="small"
                    >
                        <el-option
                            v-for="item in dicts?.finance_order_award"
                            :key="item.id"
                            :label="item.name"
                            :value="+item.value"
                        />
                    </el-select>
                    <span v-else>{{(item.award_id&&dicts?.finance_order_award.find(x=>Number(x.value)===item.award_id))?dicts?.finance_order_award.find(x=>Number(x.value)===item.award_id).name:''}}</span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="类型">
                     <!--lqy 修改查看节点的数据-->
                    <el-select
                        v-if="!disabled"
                        v-model="item.type_id"
                        size="small"
                    >
                        <el-option
                            v-for="item in dicts?.if_payment_request"
                            :key="item.value"
                            :label="item.name"
                            :value="+item.value"
                        />
                    </el-select>
                                <span v-else>{{(item.type_id&&dicts?.if_payment_request.find(x=>Number(x.value)===item.type_id))?dicts?.if_payment_request.find(x=>Number(x.value)===item.type_id).name:''}}</span>
          
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="金额">
                    <span v-if="!disabled">
                      <el-input-number
                        v-model="item.amount"
                        :precision="2"
                        :min="0"
                        size="small"
                    />
                    <span style="margin-left: 5px">元</span>
                    </span>
                   
                    <span v-else>{{item.amount}}元</span>
                </el-form-item>
            </el-col>
            <el-col :span="span">
                <el-form-item label="说明">
                     <!--lqy 修改查看节点的数据-->
                    <span v-if="!disabled">
                    <el-input
                        v-model="item.remark"
                        size="small"
                        style="flex: 1"
                    />
                    <el-button
                        style="margin-left: 5px"
                        type="warning"
                        :icon="Minus"
                        circle
                        size="small"
                        class="delCon"
                        @click="handleDelete(index)"
                    />

                    </span>
                   <span v-else>{{item.remark}}</span>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="span * 4">
                <el-form-item label="应实付款金额">
                    <span>{{ payReal }}</span>
                    <span>元</span>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="18">
                <el-form-item label="附件">
                    <el-button type="primary" link @click="handleFile">
                        查看
                    </el-button>
                </el-form-item>
            </el-col>
            <el-col :span="span"> </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-form-item
                    label="备注"
                    prop="remark"
                    style="margin-bottom: 0"
                >
                 <!--lqy 修改查看节点的数据-->
                    <el-input
                    v-if="!disabled"
                        v-model="formData.remark"
                        type="textarea"
                        placeholder="请输入备注"
                        :autosize="{ minRows: 4 }"
                        size="small"
                    ></el-input>
            
                   <span v-else>{{formData.remark}}</span>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
    <file-popup
        ref="fileRef"
        :isEdit="isEdit"
        :attachment="formData.attachment"
        @setFile="setFileFn"
    />
    <details-popup ref="detailsRef" />
</template>

<style scoped lang="scss">
// lqy修改样式
.delCon{
    position: absolute;
}
$bor-color: #eeeff0;

::v-deep .el-input.is-disabled .el-input__inner {
    background-color: #fff !important;
    border: 0 !important;
    color: #666666;
    cursor: not-allowed;
}

::v-deep .el-input.is-disabled .el-input__wrapper {
    background-color: #fff !important;
}

::v-deep .el-image__error {
    background-color: #fff !important;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
    background-color: #fff !important;
    border-color: #fff !important;
    color: #666666;
    cursor: not-allowed;
}

.el-col {
    padding: 2px;
    border-right: 1px solid $bor-color;
    border-top: 1px solid $bor-color;

    &:nth-child(4n) {
        border-right: 0;
    }
}

.el-form-item {
    margin-bottom: 0;
}

::v-deep .el-form-item__label {
    border-left: 0;
    border-top: 0;
    border-bottom: 0;
}

::v-deep .el-form-item__error {
    z-index: 10;
}

::v-deep .span {
    .el-input__inner {
        width: 133px;
    }

    .el-input__suffix-inner {
        display: none;
    }
}

::v-deep .el-form-item__error {
    top: 80%;
}
</style>
